﻿using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace OneWorks.Web.Common.ActionResults
{
    public abstract class CustomResult<TData> : ActionResult
    {
        public abstract TData GetObject();

        protected JsonSerializerSettings SerializerSettings;

        protected void InitSerialization(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "text/html";
            TData data = GetObject();
            if (SerializerSettings == null)
            {
                SetSerializerSettings();
            }
            response.Write(JsonConvert.SerializeObject(data, Formatting.Indented, SerializerSettings));
        }

        protected virtual void SetSerializerSettings()
        {
            SerializerSettings = new JsonSerializerSettings
            {              
                Converters = new List<JsonConverter>
                {
                    new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd hh:mm" }
                }
            };
        }

        public override void ExecuteResult(ControllerContext context)
        {
            InitSerialization(context);
        }
    }
}
